#include "DancingGoogler_Round.h"
#include <array>
#include <vector>
#include <math.h>
using namespace std;

DancingGoogler_Round::DancingGoogler_Round(string s)
{
	ParseLine(s);
}


DancingGoogler_Round::~DancingGoogler_Round(void)
{
}

void DancingGoogler_Round::ParseLine(string line)
{
	string temp;
	int numberOfSpaces = 0;

	for(int i = 0; i <= line.length(); i++)
	{
		if(i==line.length() || line[i] == ' ')
		{
			numberOfSpaces++;
			if(numberOfSpaces == 2)
			{
				numberOfSurprisingScores = atoi(temp.c_str());
			}
			else 
				if(numberOfSpaces == 3)
				{
					minimumScore = atoi(temp.c_str());
				}
				else if(numberOfSpaces > 3)
				{
					Scores.push_back(DancingGoogler_Score(atoi(temp.c_str())));
				}

				temp.clear();
		}
		else
		{
			temp += line[i];
		}
	}
}


int DancingGoogler_Round::MaxNumberOfGooglers()
{
	int result = 0;
	int numberOfSurprisingScoresLeft = numberOfSurprisingScores;
	for(int i = 0; i < Scores.size(); i++)
	{
		vector<array<int,3>> possibleMarks = Scores[i].GetPossibleMarks();
		bool resultFound = false;
		for(int j = 0; j < possibleMarks.size(); j++)
		{
			if(possibleMarks[j][0] >= minimumScore || possibleMarks[j][1] >= minimumScore || possibleMarks[j][2] >= minimumScore)
			{
				if(!IsSurprising(possibleMarks[j]))
				{
					result++;
					resultFound = true;
					break;
				}
			}
		}

		if(!resultFound)
		{
			for(int j = 0; j < possibleMarks.size(); j++)
			{
				if(numberOfSurprisingScoresLeft > 0 && (possibleMarks[j][0] >= minimumScore || possibleMarks[j][1] >= minimumScore || possibleMarks[j][2] >= minimumScore))
				{
					numberOfSurprisingScoresLeft--;
					result++;
					resultFound = true;
					break;
				}
			}
		}
	}

	return result;
}


bool DancingGoogler_Round::IsSurprising(array<int,3> marks)
{
	return abs(marks[0] - marks[1]) == 2 || abs(marks[0] - marks[2]) == 2 || abs(marks[1] - marks[2]) == 2;
}